package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.R;
import com.itheima.dto.SetmealDto;
import com.itheima.pojo.Category;
import com.itheima.pojo.Setmeal;
import com.itheima.pojo.SetmealDish;
import com.itheima.service.CategoryService;
import com.itheima.service.SetmealDishService;
import com.itheima.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/*
 * Rest模式
 * */
@RestController
@Slf4j
@RequestMapping("/setmeal")
public class SetmealController {
    @Autowired
    private SetmealService setmealService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private SetmealDishService setmealDishService;

    /**
     * 分页查询
     *
     * @param page     当前页码
     * @param pageSize 每页显示的条数
     * @param name     套餐名称
     * @return 分页数据
     */
    @GetMapping("page")
    public R<Page> page(Integer page, Integer pageSize, String name) {
        //创建分页构造器
        Page<Setmeal> setmealPage = new Page(page, pageSize);
        Page<SetmealDto> setmealDtoPage = new Page();

        //条件构造器
        LambdaQueryWrapper<Setmeal> setmealQueryWrapper = new LambdaQueryWrapper<>();

        //模糊查询
        setmealQueryWrapper.like(StringUtils.isNotBlank(name), Setmeal::getName, name);

        //排序条件
        setmealQueryWrapper.orderByDesc(Setmeal::getUpdateTime);

        //分页查询
        setmealService.page(setmealPage, setmealQueryWrapper);

        //对象拷贝
        BeanUtils.copyProperties(setmealPage, setmealDtoPage, "records");

        List<Setmeal> setmeals = setmealPage.getRecords();

        List<SetmealDto> setmealDtos = setmeals.stream().map((item) -> {
            SetmealDto setmealDto = new SetmealDto();
            //对象拷贝
            BeanUtils.copyProperties(item, setmealDto);

            //根据菜品及套餐分类的Id查询菜品及套餐分类的分类名称
            Category category = categoryService.getById(item.getCategoryId());
            setmealDto.setCategoryName(category.getName());

            return setmealDto;
        }).collect(Collectors.toList());

        setmealDtoPage.setRecords(setmealDtos);

        return R.success(setmealDtoPage);
    }

    /**
     * 新增套餐
     *
     * @param setmealDto 接受前端数据
     * @return
     */
    @Transactional
    @PostMapping
    public R<String> save(@RequestBody SetmealDto setmealDto) {
        try {
            //保存套餐的基本信息
            setmealService.save(setmealDto);

            List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes().stream().map((item) -> {
                item.setSetmealId(setmealDto.getId().toString());
                item.setIsDeleted(0);
                return item;
            }).collect(Collectors.toList());

            //保存套餐菜品信息
            setmealDishService.saveBatch(setmealDishes);

            return R.success("新增成功!");
        } catch (Exception e) {
            log.info("新增失败!");
            throw new RuntimeException(e);
        }
    }


    /**
     * 根据套餐id查询对应的套餐信息和套餐菜品信息,并回显到页面
     *
     * @param id 套餐id
     * @return
     */
    @GetMapping("{id}")
    public R<SetmealDto> getById(@PathVariable("id") Long id) {

        SetmealDto setmealDto = new SetmealDto();

        //根据套餐id查询对应的套餐信息
        LambdaQueryWrapper<Setmeal> setmealQueryWrapper = new LambdaQueryWrapper<>();
        setmealQueryWrapper.eq(Setmeal::getId, id);
        Setmeal setmeal = setmealService.getOne(setmealQueryWrapper);
        //对象拷贝
        BeanUtils.copyProperties(setmeal, setmealDto);

        //根据套餐id查询对应的套餐菜品信息
        LambdaQueryWrapper<SetmealDish> setmealDishQueryWrapper = new LambdaQueryWrapper<>();
        setmealDishQueryWrapper.eq(SetmealDish::getSetmealId, id);
        List<SetmealDish> setmealDishes = setmealDishService.list(setmealDishQueryWrapper);
        setmealDto.setSetmealDishes(setmealDishes);

        return R.success(setmealDto);
    }

    /**
     * 修改套餐
     *
     * @param setmealDto 接受前端数据
     * @return
     */
    @Transactional
    @PutMapping
    public R<String> update(@RequestBody SetmealDto setmealDto) {

        try {
            //根据套餐id修改对应的套餐的基本信息
            setmealService.updateById(setmealDto);

            //根据套餐id删除对应的所有的套餐菜品信息
            LambdaQueryWrapper<SetmealDish> setmealDishQueryWrapper = new LambdaQueryWrapper<>();
            setmealDishQueryWrapper.eq(SetmealDish::getSetmealId, setmealDto.getId());
            setmealDishService.remove(setmealDishQueryWrapper);

            List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes().stream().map((item) -> {
                item.setSetmealId(setmealDto.getId().toString());
                item.setIsDeleted(0);
                return item;
            }).collect(Collectors.toList());

            //新增套餐菜品
            setmealDishService.saveBatch(setmealDishes);

            return R.success("修改成功!");
        } catch (Exception e) {
            log.info("修改失败!");
            throw new RuntimeException(e);
        }
    }

    /**
     * 修改套餐的状态
     * 状态：0:停用 1:启用
     * @param status 将状态值修改成这个参数的状态值
     * @param ids    要修改状态的套餐id
     * @return
     */
    @PostMapping("/status/{status}")
    public R<String> updateStatus(@PathVariable("status") Integer status, Long[] ids) {
        try {
            Setmeal setmeal = new Setmeal();
            for (Long id : ids) {
                setmeal.setId(id);
                setmeal.setStatus(status);
                if (status == 0) {
                    //将套餐的状态修改成停售
                    setmealService.updateById(setmeal);
                } else if (status == 1) {
                    //将套餐的状态修改成起售
                    setmealService.updateById(setmeal);
                } else {
                    return R.error("修改失败!");
                }
            }
            return R.success("修改成功!");
        } catch (Exception e) {
            log.info("修改失败!");
            throw new RuntimeException(e);
        }
    }

    /**
     * 根据套餐id删除对应的套餐和套餐菜品
     * @param ids 套餐id
     * @return
     */
    @Transactional
    @DeleteMapping
    public R<String> delete(Long[] ids){
        try {
            for (Long id : ids) {
                //根据套餐id删除对应的套餐
                setmealService.removeById(id);

                //根据套餐id删除对应的套餐菜品
                LambdaQueryWrapper<SetmealDish> setmealDishQueryWrapper = new LambdaQueryWrapper<>();
                setmealDishQueryWrapper.eq(SetmealDish::getSetmealId,id);
                setmealDishService.remove(setmealDishQueryWrapper);
            }

            return R.success("删除成功!");
        } catch (Exception e) {
            log.info("删除失败!");
            throw new RuntimeException(e);
        }
    }
}
